package com.tceasy.gateway.controller;

import com.tceasy.gateway.Constants;
import com.tceasy.gateway.aop.Check;
import com.tceasy.gateway.domain.OpenUser;
import com.tceasy.gateway.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by zhanghuan on 2016/4/12.
 */
@Controller
@RequestMapping("/login")
@Check
public class LoginController extends AbstractController{

    Logger logger= LoggerFactory.getLogger(LoginController.class);

    @Autowired
    UserService userService;

    /**
     * 登录
     * @param user
     * @return
     */
    @RequestMapping(value="/login")
    @Check
    public ModelAndView login(HttpServletRequest request,ModelAndView view,OpenUser user){
        try {
            userService.login(user.getUsername(),user.getPasswd());
            getSession(request).setAttribute(Constants.USER_IN_SESSION,user.getUsername());
            return main(view);
        } catch (Exception e) {
            String msg=e.getMessage();
            logger.error(e.toString());
            view.addObject("msg",msg);
            view.setViewName("redirect:/login.jsp");
            return view;
        }
    }

    /**
     * 登出
     * @return
     */
    @RequestMapping("/logout")
    public String logout(HttpServletRequest request){
        getSession(request).removeAttribute(Constants.USER_IN_SESSION);
        return "redirect:/login";
    }

    /**
     * 主页
     * @param view
     * @return
     */
    @RequestMapping(value="/main")
    public ModelAndView main(ModelAndView view){
        view.setViewName("main");
        return view;
    }


    /**
     * 主页
     * @param view
     * @return
     */
    @RequestMapping(value="/index")
    public ModelAndView index(ModelAndView view){
        view.setViewName("index");
        return view;
    }
}
